package icbc.nav.view
{
	import com.greensock.TweenLite;
	import com.greensock.easing.Strong;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	
	import icbc.app.AppGlobal;
	import icbc.app.control.Alert;
	
	public class MainView extends Sprite
	{
		private var backgroundImage:String = null;
		private var image:Sprite;
		private var frontView:FrontView;
		private var menuView:MenuView;

		public function MainView()
		{
			super();
			addEventListener(Event.ADDED_TO_STAGE, initStage);
		}
		
		private function initStage(evt:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, initStage);
			stage.addEventListener(Event.RESIZE, initMain);
			stage.dispatchEvent(new Event(Event.RESIZE));
		}
		
		private function initMain(evt:Event = null):void
		{
			if(stage.stageWidth>0)
				stage.removeEventListener(Event.RESIZE, initMain);
			else return;
			initApp();
		}
		
		private function initApp():void
		{
			loadBackground();
			goFront();
		}
		
		private function goFront():void
		{
			frontView = new FrontView();
			frontView.onClose.addOnce(frontCloseHandler);
			addChild(frontView);
		}
		
		private function frontCloseHandler():void
		{
			var spriteTween:TweenLite = new TweenLite(frontView, 3,{
				ease:Strong.easeInOut, alpha:0,
				onComplete:function():void {
					removeChild(frontView);
					goMenu();
				}
			});
		}

		private function goMenu():void
		{
			menuView = new MenuView();
			addChild(menuView);
		}

		private function loadBackground():void
		{
			image = new Sprite();
			addChild(image);
			backgroundImage = AppGlobal.PATH_BACKGROUND;
			if(backgroundImage == null)
				return;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.load(new URLRequest(AppGlobal.combinePath(backgroundImage)));
			image.addChild(loader);
		}
		
		private function onIOError(evt:IOErrorEvent):void
		{
			trace("MainView.Image["+ backgroundImage +"].IOError: "+ evt.text);
		}		
		
		private function imageComplete(evt:Event):void
		{
			var image:DisplayObject = (evt.target as LoaderInfo).content;
		}
	}
}